<template>
    <div>
        <!-- 面包屑导航区域 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>参数列表</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 卡片视图区域 -->
        <el-card>
            <!-- 警告区域 -->
            <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" show-icon></el-alert>
            <!-- 选择商品分类区域 -->
            <el-row class="cat_opt">
                <el-col :span="8">
                    <span>选择商品分类：</span>
                    <!-- 选择商品分类的级联选择框 -->
                    <el-cascader clearable :options="cateslist" :props="cateProps" v-model="selectedCateKeys" @change="ParentCateChangd">
                    </el-cascader>
                </el-col>
            </el-row>
            <el-tabs v-model="activeName" @tab-click="handleTabClick">
                 <!-- 添加动态参数的区域 -->
                <el-tab-pane label="动态参数" name="many">
                      <el-button type="primary" :disabled="isBtnDisabled" size="mini" @click="addDialogVisible = true">添加参数</el-button>
                        <!-- 动态参数表格 -->
                        <el-table :data="manyCateParam" border style="width: 100%" stripe>
                            <el-table-column type="expand">
                            </el-table-column>
                            <el-table-column label="参数名称" prop="attr_name"> </el-table-column>
                            <el-table-column label="操作">
                                <template slot-scope="scope">
                                <el-button type="primary" icon="el-icon-edit" size="small" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                                    <el-button type="danger" icon="el-icon-delete" size="small" @click="removeParams(scope.row.attr_id)">删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                </el-tab-pane>
                 <!-- 添加静态属性的区域 -->
                <el-tab-pane label="静态属性" name="only">
                      <el-button type="primary" :disabled="isBtnDisabled" size="mini" @click="addDialogVisible = true">添加属性</el-button>
                        <!-- 静态属性表格 -->
                        <el-table :data="onlyCateAttr" border style="width: 100%" stripe>
                            <el-table-column type="expand">
                            </el-table-column>
                            <el-table-column label="属性名称" prop="attr_name"> </el-table-column>
                            <el-table-column label="操作">
                                <template slot-scope="scope">
                                <el-button type="primary" icon="el-icon-edit" size="small" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                                    <el-button type="danger" icon="el-icon-delete" size="small" @click="removeParams(scope.row.attr_id)">删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                </el-tab-pane>
             </el-tabs>
        </el-card>

         <!-- 添加参数的对话框 -->
        <el-dialog :title="'添加' + titleText" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">
        <el-form :model="addForm" :rules="FormRules" ref="addFormRef" label-width="100px">
            <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="addForm.attr_name"></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="addDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addParams">确 定</el-button>
        </span>
        </el-dialog>
         <!-- 修改参数的对话框 -->
        <el-dialog :title="'修改' + titleText" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
        <el-form :model="editForm" :rules="FormRules" ref="editFormRef" label-width="100px">
            <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="editForm.attr_name"></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="editDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="editParams">确 定</el-button>
        </span>
        </el-dialog>
    </div>
</template>
<script>
export default {
  data () {
    return {
      // 所有分类数据
      cateslist: [],
      // 指定级联选择器的配置对象
      cateProps: {
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id'
      },
      // 选中的父级分类的Id数组
      selectedCateKeys: {},
      // 被激活的页签的名称
      activeName: 'many',
      // 动态分类参数数据
      manyCateParam: [],
      // 静态属性数据
      onlyCateAttr: [],
      // 控制添加对话框显示状态
      addDialogVisible: false,
      // 控制修改对话框显示状态
      editDialogVisible: false,
      // 保存添加参数的数据
      addForm: {
        attr_name: ''
      },
      // 保存修改参数的数据
      editForm: {
      },
      // 表单的验证规则对象
      FormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getCatesList()
  },
  methods: {
    // 获取所有分类数据
    async getCatesList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.cateslist = res.data
    },
    // 根据分类Id获取参数数据
    async getParamsList () {
      if (this.selectedCateKeys.length !== 3) {
        this.manyCateParam = []
        this.onlyCateAttr = []
        return
      }
      // 当前分类ID
      const { data: res } = await this.$http.get(`categories/${this.CateId}/attributes`, {
        params: { sel: this.activeName }
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // 将值给赋值给data
      this.activeName === 'many' ? this.manyCateParam = res.data : this.onlyCateAttr = res.data
    },
    // 选择框发生改变是触发这个函数
    ParentCateChangd () {
      this.getParamsList()
    },
    // 监听el-tabs表格切换的时候触发
    handleTabClick () {
      this.getParamsList()
    },
    // 关闭添加对话框时重置表单
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },
    // 关闭修改对话框时重置表单
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },
    // 点击按钮添加参数
    addParams () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(`categories/${this.CateId}/attributes`, {
          attr_name: this.addForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg || '添加参数失败')
        this.$message.success(res.meta.msg)
        this.getParamsList()
        this.addDialogVisible = false
      })
    },
    // 点击显示修改框
    async showEditDialog (attrId) {
      const { data: res } = await this.$http.get(`categories/${this.CateId}/attributes/${attrId}`, {
        attr_sel: this.activeName
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg || '数据获取失败')
      this.editForm = res.data
      this.editDialogVisible = true
    },
    // 点击确定修改参数
    editParams () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(`categories/${this.CateId}/attributes/${this.editForm.attr_id}`, {
          attr_name: this.editForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg || '修改失败')
        this.$message.success(res.meta.msg || '修改成功')
        // 重新渲染数据
        this.getParamsList()
        // 关闭对话框
        this.editDialogVisible = false
      })
    },
    // 点击进行删除操作
    async removeParams (attrId) {
      const confirmResult = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') return this.$message.info('取消了删除')
      const { data: res } = await this.$http.delete(`categories/${this.CateId}/attributes/${attrId}`)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg || '删除失败')
      this.$message.success('删除成功')
      this.getParamsList()
    }
  },
  computed: {
    // 如果按钮需要被禁用，则返回true，否则返回false
    isBtnDisabled () {
      if (this.selectedCateKeys.length !== 3) {
        return true
      } else {
        return false
      }
    },
    titleText () {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    },
    // 计算当前分类ID
    CateId () {
      if (this.selectedCateKeys.length === 3) {
        return this.selectedCateKeys[2]
      }
      return null
    }
  }
}
</script>
<style lang="scss" scoped>
    .cat_opt{
        margin-top: 15px;
    }
    .el-cascader {
        width: 50%;
    }
    .el-tabs{
        margin-top: 15px;
    }
</style>
